package wms.api.modules.menu.service;

import wms.api.core.bean.TreeEntity;
import wms.api.core.utils.Utils;
import wms.api.modules.menu.entity.MenuEntity;
import wms.api.modules.menu.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuService {
	@Autowired
	private MenuMapper menuMapper;

	/**
	 * 查询菜单列表
	 * @param menuEntity
	 * @return
	 */
	public List<TreeEntity> list(MenuEntity menuEntity) {
		return Utils.convertTree(menuMapper.findList(menuEntity));
	}

	/**
	 * 查询菜单详情
	 * @param menuId
	 * @return
	 */
	public MenuEntity detail(String menuId) {
		List<MenuEntity> menuList = menuMapper.getChildren(menuId);
		MenuEntity menu = menuMapper.getById(menuId);
		if(menu != null && menuList.isEmpty()) {
			return null;
		}

		menuList.add(0, menuMapper.getById(menuId));
		Map<String, MenuEntity> menuMap = new HashMap<>();
		for(MenuEntity m : menuList) {
			MenuEntity parent = menuMap.get(m.getParentId());
			if(parent != null) {
				List<MenuEntity> children = parent.getChildren();
				if(children == null) {
					children = new ArrayList<>();
				}
				children.add(m);
			}
			menuMap.put(m.getId(), m);
		}

		return menu;
	}

	/**
	 * 新增菜单
	 * @param menuEntity
	 * @return
	 */
	public int add(MenuEntity menuEntity) {
		return menuMapper.insert(menuEntity);
	}

	/**
	 * 编辑菜单
	 * @param menuId
	 * @param menuEntity
	 * @return
	 */
	public int update(String menuId, MenuEntity menuEntity) {
		menuEntity.setId(menuId);
		return menuMapper.update(menuEntity);
	}

	/**
	 * 删除菜单
	 * @param menuId
	 * @return
	 */
	@Transactional
	public int delete(String menuId) {
		return menuMapper.delete(menuId) + menuMapper.deleteChildren(menuId);
	}

	/**
	 * 根据code查询菜单
	 * @param systemId
	 * @param menuCode
	 * @return
	 */
	public MenuEntity getByCode(String systemId, String menuCode) {
		return menuMapper.getByCode(systemId, menuCode);
	}

	/**
	 * 根据角色查询菜单
	 * @param roleIds
	 * @return
	 */
	public List<MenuEntity> getMenuByRoles(List<String> roleIds) {
		return menuMapper.getMenuByRoles(roleIds);
	}
}
